<template>
	<page-meta>
		<navigation-bar :title="nbTitle" :subtitle-color="nbFrontColor" :loading="nbLoading" :front-color="nbFrontColor"
			:background-color="nbBackgroundColor" />
	</page-meta>
	<view class="example">

		<view v-if="isShow==true" v-cloak>
			<uni-forms ref="form" :model="user">
				<uni-forms-item label="班级" name="classId" required>
					<uni-data-picker :localdata="items" popup-title="请选择班级" v-model="user.classId">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="验证码" name="classPassword">
					<uni-easyinput type="password" v-model="user.classPassword" placeholder="请输入验证码" />
				</uni-forms-item>
			</uni-forms>

			<view class="button-group">
				<button class="btn" @click="submit(1)">加入班级</button>
			</view>
		</view>
		<view v-if="isShow==false" v-cloak>
			<uni-list>

				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'contact'}" title="班级" :rightText="className" />
			</uni-list>
			<view class="button-group">
				<button class="btnBack" type="warn" @click="submit(2)">退出班级</button>
			</view>
		</view>
	</view>

</template>

<script>
	import {
		profileClass,
		updateUserClass,
		deleteUserClass,
		listType
	} from "@/api/system/user"
	export default {
		data() {
			return {
				nbTitle: '加入班级',
				nbLoading: false,
				nbFrontColor: '#ffffff',
				nbBackgroundColor: '#fcc10d',
				items: [],
				oldClassId: "",
				isShow: true,
				data: [],
				user: {
					classId: "",
					classPassword: "",
				},
				rules: {
					classId: {
						rules: [{
							required: true,
							errorMessage: '班级不能为空'
						}]
					},
					classPassword: {
						rules: [{
							required: true,
							errorMessage: '班级验证码不能为空'
						}]
					},
				}
			}
		},
		mounted() {
			this.getUser()
		},
		onLoad() {

			listType().then((response) => {
				this.data = response.data
				const data = {
					deptId: 0,
					typeName: "顶级节点",
					children: []
				};

				for (let i = 0; i < response.data.length; i++) {
					this.$set(response.data[i], "text", response.data[i].typeName)
					this.$set(response.data[i], "value", response.data[i].deptId + "")
				}
				data.children = this.handleTree(response.data, "deptId", "parentId");

				for (let i = 0; i < data.children.length; i++) {
					this.items.push(data.children[i])
				}

			})
		},
		onReady() {
			if (this.isShow == true) {
				this.$refs.form.setRules(this.rules)
			}
		},
		methods: {
			handleTree(data, id, parentId, children) {
				let config = {
					id: id || 'id',
					parentId: parentId || 'parentId',
					childrenList: children || 'children'
				};
				var childrenListMap = {};
				var nodeIds = {};
				var tree = [];
				for (let d of data) {
					let parentId = d[config.parentId];
					if (childrenListMap[parentId] == null) {
						childrenListMap[parentId] = [];
					}
					nodeIds[d[config.id]] = d;
					childrenListMap[parentId].push(d);
				}
				for (let d of data) {
					let parentId = d[config.parentId];
					if (nodeIds[parentId] == null) {
						tree.push(d);
					}
				}
				for (let t of tree) {
					adaptToChildrenList(t);
				}

				function adaptToChildrenList(o) {
					if (childrenListMap[o[config.id]] !== null) {
						o[config.childrenList] = childrenListMap[o[config.id]];
					}
					if (o[config.childrenList]) {
						for (let c of o[config.childrenList]) {
							adaptToChildrenList(c);
						}
					}
				}
				return tree;
			},

			getUser() {
				profileClass().then(response => {
					this.user = response.data
					// console.log(response.data);
					this.oldClassId = response.data.classId
					if (this.user.classId != null) {
						this.isShow = false
					}
				})
			},
			submit(ref) {
				if (ref == 1) {
					this.$refs.form.validate().then(res => {
						for (let i = 0; i < this.data.length; i++) {
							if (this.data[i].deptId == this.user.classId) {
								if (this.data[i].parentId == 0) {
									return uni.showToast({
										title: '请选择具体的班级',
										icon: 'error'
									})

								}

							}
						}

						updateUserClass(this.user.classId, this.user.classPassword).then(response => {
							if (response.code == 200) {
								this.$store.commit('SET_CLASSID', this.user.classId)
								// this.$store.dispatch('SET_CLASSID', this.user.classId)
								uni.showToast({
									title: "加入班级成功",
									duration: 2000
								})

								setTimeout(() => {
									uni.navigateBack({
										delta: 2
									})
								}, 1000)
							}
						})
					})


				} else if (ref = 2) {
					uni.showModal({
						title: '提示',
						content: '是否退出当前班级',
						success: (res) => {
							this.$store.commit('SET_CLASSID', 0)
							if (res.confirm) {
								deleteUserClass().then(res => {
									if (res.code == 200) {
										uni.showToast({
											title: '退出成功',
											duration: 2000,
										});
										setTimeout(() => {
											uni.navigateBack({
												delta: 2
											})
											uni.removeTabBarBadge({
												index: 2
											})
										}, 1000)

									}
								})
							} else if (res.cancel) {}
						}
					});

				}
			}
		},
		computed: {
			className() {

				for (let i = 0; i < this.items.length; i++) {
					for (let j = 0; j < this.items[i].children.length; j++) {
						if (this.oldClassId == this.items[i].children[j].deptId) {
							return this.items[i].children[j].text;
						}
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	[v-cloak] {
		display: none;
	}

	page {
		background-color: #ffffff;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.btn {
		width: 720rpx;
		height: 70rpx;
		background-color: #f7cb50;
		color: #ffffff;
		font-size: 24rpx;
		line-height: 60rpx;
	}

	.btnBack {
		width: 720rpx;
		height: 70rpx;
		background-color: darkred;
		color: #ffffff;
		font-size: 24rpx;
		line-height: 60rpx;
	}
</style>
